<template>
    <div>
        <el-button text @click="showAddBox" v-if="flagShowControl === 'addbutton'">
            添加
        </el-button>
        <el-button text class="editControl" @click="showAddBox" v-if="flagShowControl === 'editbutton'">
            编辑
        </el-button>
        <el-dialog v-model="dialogFormVisible" title="新增体检套餐" :append-to-body="true" width="63%">
            <el-form :model="form" ref="formRef">
                <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                    <el-tab-pane label="基本信息" name="first">
                        <div class="baseInfo">
                            <div class="top-box">
                                <div class="left-box">
                                    <el-form-item label="套餐名称" :label-width="formLabelWidth" :rules="[
                                        { required: true, message: '必须填入体检项名称' }]" prop="projectname">
                                        <el-input v-model="form.projectname" autocomplete="off" />
                                    </el-form-item>
                                    <el-form-item label="套餐ID" :label-width="formLabelWidth" :rules="[
                                        { required: true, message: '请输入套餐ID' }]" prop="projectid">
                                        <el-input v-model="form.projectid" autocomplete="off" />
                                    </el-form-item>
                                    <el-form-item label="是否启用" :rules="[
                                        { required: true }
                                    ]" prop="isUse" label-width="140px">
                                        <el-switch v-model="form.isUse"></el-switch>
                                    </el-form-item>
                                    <el-form-item label="适用标签" :rules="[
                                        { required: true }
                                    ]" prop="checkBoxSetMeal" label-width="140px">
                                        <el-checkbox-group v-model="form.checkBoxSetMeal">
                                            <el-checkbox-button v-for="item in setMeal" :key="item" :label="item">{{
                                                item
                                            }}</el-checkbox-button>
                                        </el-checkbox-group>

                                    </el-form-item>
                                    <el-form-item label="有效时间截至" :label-width="formLabelWidth" prop="choiceTime">
                                        <el-input v-model="form.choiceTime" autocomplete="off" placeholder="选择时间" />
                                    </el-form-item>
                                    <el-form-item label="原价" :rules="[
                                        { required: true, message: '请输入套餐原价' }
                                    ]" :label-width="formLabelWidth" prop="originPrice">
                                        <el-input v-model="form.originPrice" autocomplete="off" placeholder="输入原价" />
                                    </el-form-item>
                                    <el-form-item label="售价" :rules="[
                                        { required: true, message: '请输入套餐售价' }
                                    ]" :label-width="formLabelWidth" prop="salePeice">
                                        <el-input v-model="form.salePeice" autocomplete="off" placeholder="输入售价" />
                                    </el-form-item>
                                </div>
                                <div class="right-box">
                                    <el-form-item label="适用城市" :rules="[{ required: true, message: '选择城市' }]">
                                        <selectCity ref="selectCityRef" @change="changeCityHandle"></selectCity>

                                    </el-form-item>
                                    <el-form-item label="适用机构" :rules="[{ required: true, message: '选择适用机构' }]"
                                        porp="suitMechanism" placeholder="全部">
                                        <el-select v-model="form.suitMechanism" @change="changeSuitMechanism">
                                            <el-option v-for="item in suitMechanism" :key="item.value" :label="item.label"
                                                :value="item.value"></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="分支机构" prop="branchMechanism"
                                        :rules="[{ required: true, message: '选择分支机构' }]">
                                        <el-transfer v-model="form.branchMechanism" filterable :filter-method="filterMethod"
                                            filter-placeholder="请输入内容" :data="dataPartNameM" :titles="['机构列表', '已选机构']" />
                                    </el-form-item>
                                </div>
                            </div>
                            <div class="bottom-box">
                                <el-form-item label="套餐介绍" :rules="[
                                    { required: true, message: '请输入套餐介绍' }
                                ]" prop="setMealIntroduce" :label-width="formLabelWidth">
                                    <el-input v-model="form.setMealIntroduce" :rows="2" type="textarea"
                                        placeholder="请输入套餐介绍"></el-input>
                                </el-form-item>
                                <el-form-item label="使用规则" :rules="[
                                    { required: true, message: '请输入套餐使用规则' }
                                ]" prop="setMealUseRule" :label-width="formLabelWidth">
                                    <el-input v-model="form.setMealUseRule" :rows="2" type="textarea"
                                        placeholder="请输入套餐使用规则"></el-input>
                                </el-form-item>
                                <el-form-item label="套餐组成" :rules="[
                                    { required: true, message: '请输入套餐组成' }
                                ]" prop="setMealForm" :label-width="formLabelWidth">
                                    <el-input v-model="form.setMealForm" :rows="2" type="textarea"
                                        placeholder="请输入套餐组成"></el-input>
                                </el-form-item>
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="套餐组成" name="second">
                        <div style="display: flex;">
                            <dialogAdd @updateData="getAddedData" @hideClient="dialogFormVisible = false
                            "></dialogAdd>
                            <el-button style="margin-left: 10px;" @click="delMealForm">删除</el-button>
                        </div>
                        <el-form-item prop="tableFormOption">
                            <el-table :data="tableFormOption" stripe :border="true" :highlight-current-row="false"
                                style="width: 100%" :cell-style="{ 'text-align': 'center', 'font-size': '12px' }"
                                :header-cell-style="{
                                    'text-align': 'center',
                                    'background-color': '#f9fafc',
                                    'color': '#666'
                                }" @selection-change="handleSelectionChangeTableFormOption">
                                <el-table-column type="selection" min-width="53" />
                                <el-table-column prop="projectname" label="项目名称" width="180" />
                                <el-table-column prop="testrange" label="检查范围" width="180" />
                                <el-table-column prop="checkupmeaning" label="检查意义" />
                                <el-table-column prop="suituse" label="适用标签" />
                                <el-table-column prop="originprice" label="原价" />
                                <el-table-column prop="saleprice" label="售价" />
                            </el-table>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="加项包" name="third">
                        <div style="display: flex;">
                            <aAddOptionPackage @updateData="getAddedPackageData" @hideClient="dialogFormVisible = false
                            "></aAddOptionPackage>
                            <el-button style="margin-left: 10px;" @click="delAddPackage">删除</el-button>
                        </div>
                        <el-form-item prop="addOptionPackage">
                            <el-table :data="addOptionPackage" stripe :border="true" :highlight-current-row="false"
                                style="width: 100%" :cell-style="{ 'text-align': 'center', 'font-size': '12px' }"
                                :header-cell-style="{
                                    'text-align': 'center',
                                    'background-color': '#f9fafc',
                                    'color': '#666'
                                }" @selection-change="handleSelectionChangeAddOptionPackage">
                                <el-table-column type="selection" min-width="53" />
                                <el-table-column prop="projectname" label="项目名称" width="180" />
                                <el-table-column prop="testrange" label="检查范围" width="180" />
                                <el-table-column prop="checkupmeaning" label="检查意义" />
                                <el-table-column prop="suituse" label="适用标签" />
                                <el-table-column prop="originprice" label="原价" />
                                <el-table-column prop="saleprice" label="售价" />
                            </el-table>
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="formReset(formRef)">取消</el-button>
                    <el-button type="primary" @click="submit(formRef)">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>


    </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { ElMessage, type TabsPaneContext } from 'element-plus'
import selectCity from "@/component/selectCity.vue"
import type { FormInstance } from 'element-plus'
import service from '@/utils/service';
import dialogAdd from './dialogAdd.vue'
import aAddOptionPackage from './aAddOptionPackage.vue';
import { ignorableWatch } from '@vueuse/shared';

// 控制表单的显示隐藏
const activeName = ref('first')
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const formRef = ref<FormInstance>()
const selectCityRef = ref(null)
const emit = defineEmits(["addChange"])
interface Iprops {
    flagShowControl: string,
    getDataById?: string | number
}
const props = defineProps<Iprops>()


// 定义套餐组成类型
interface ItableFormOption {
    projectname: string,
    testrange: string,
    checkupmeaning: string,
    suituse: string,
    originprice: number,
    saleprice: number,
    id?: string | number
}
const tableFormOption = reactive<ItableFormOption[]>([])
// 定义加项包
interface IaddOptionPackage {
    projectname: string,
    testrange: string,
    checkupmeaning: string,
    suituse: string,
    originprice: number,
    saleprice: number,
    id?: string | number
}
const addOptionPackage = reactive<IaddOptionPackage[]>([])
// 定义表单数据类型
interface Iform {
    "projectname": string,
    "projectid": string,
    "isUse": boolean,
    "checkBoxSetMeal": string[],
    "choiceTime"?: string,
    "originPrice": number,
    "salePeice": number,
    // 选择省市
    "province": string,
    "city": string,
    "suitMechanism": string,
    "branchMechanism": string[],
    "setMealIntroduce": string,
    "setMealUseRule": string,
    "setMealForm": string,
    "tableFormOption": ItableFormOption[],
    "addOptionPackage": IaddOptionPackage[]

}
const form: Iform = reactive({
    "projectname": '',
    "projectid": "",
    "isUse": true,
    "checkBoxSetMeal": [],
    "choiceTime": "",
    "originPrice": 299,
    "salePeice": 199,
    // 选择省市
    "province": "",
    "city": "",
    "suitMechanism": "",
    "branchMechanism": [""],
    "setMealIntroduce": "",
    "setMealUseRule": "",
    "setMealForm": "",
    "tableFormOption": [],
    "addOptionPackage": []
})

// 适用标签(多选框)
// const checkAll = ref(false)
// const isIndeterminate = ref(true)
// const checkboxGroup2 = ref(['Shanghai'])
const setMeal = ['男性套餐', '女性套餐', '老人套餐', '入职体检']
const showAddBox = (e: MouseEvent) => {
    let target = e.target;
    if ((target as HTMLElement).nodeName == "I" || (target as HTMLElement).nodeName == "SPAN") {
        target = (target as HTMLElement).parentNode;
    }
    (target as HTMLElement).blur();
    dialogFormVisible.value = true
}
const handleClick = (tab: TabsPaneContext, event: Event) => {
    // ???
}

// 监听city变化
const changeCityHandle = (province: string, city: string) => {
    service({
        url: "/provinces",
        params: {
            province
        }
    }).then(res => {
        if (res.data) {
            let arrMechanism = res.data[0].city.filter((item: any) => item.cityName === city)
            suitMechanism.length = 0
            arrMechanism[0].mechanism.forEach((item: any) => {
                suitMechanism.push(
                    {
                        value: item.name,
                        label: item.name,
                    }
                )
            })
        }
    })
}
// 适用机构：
interface IsuitMechanism {
    label: string,
    value: string
}

const suitMechanism = reactive<IsuitMechanism[]>([])
// 改变适用机构
const changeSuitMechanism = (val: string) => {

    service({
        url: `/provinces`,
        params: {
            province: (selectCityRef.value as any).provinceValue
        }
    }).then((res: any) => {
        if (res.data) {
            let arrMechanism = res.data[0].city.filter((item: any) => item.cityName === (selectCityRef.value as any).cityValue)
            let arrPartName = arrMechanism[0].mechanism.filter((item: any) => item.name === val)
            states.length = 0
            arrPartName[0].partName.forEach((item: any) => {
                states.push(item.name)
            })
            dataPartNameM.length = 0
            generateData().forEach((item: any) => {

                dataPartNameM.push({ ...item })
            })
            console.log(dataPartNameM);
        }
    })
}
// 分支机构(穿梭框)
interface Option {
    key: string
    label: string
    initial?: string
}
const dataPartName: Option[] = []

const states = <string[]>[]

const generateData = () => {
    dataPartName.length = 0
    states.forEach(city => {
        dataPartName.push({
            label: city,
            key: city,
            initial: city.slice(0, 2),
        })
    })
    return dataPartName
}

let dataPartNameM = reactive<Option[]>([])

// const value = ref([])
// 套餐介绍
// const textarea = ref("")
const filterMethod = (query: any, item: any) => {
    return item.initial.toLowerCase().includes(query.toLowerCase())
}
// 获取套餐组成数据
const getTableFormOptionData = () => {
    service({
        url: `tableFormOption`
    }).then(res => {
        if (res.data) {
            tableFormOption.length = 0
            tableFormOption.push(...res.data)
        }
    })
}
getTableFormOptionData()
const handleSelectionChangeTableFormOption = (val: ItableFormOption[]) => {
    form.tableFormOption.length = 0
    form.tableFormOption.push(...val)
}

// 套餐组成添加按钮

// 参套组成删除
const delMealForm = () => {
    if (form.tableFormOption) {

        form.tableFormOption.forEach(item => {
            service({
                url: `tableFormOption/${item.id}`,
                method: "delete"
            })
        })
        getTableFormOptionData()
    } else {
        ElMessage({
            showClose: true,
            message: "请选择你需要操作的数据！",
            type: "warning"
        })
    }
}

// 获取套餐组成添加后的数据
const getAddedData = () => {
    getTableFormOptionData()
}
// 获取加项包数据
const getAddOptionPackageData = () => {
    service({
        url: `addOptionPackage`
    }).then(res => {
        if (res.data) {
            addOptionPackage.length = 0
            addOptionPackage.push(...res.data)
        }
    })
}
getAddOptionPackageData()
// 加项包删除
const delAddPackage = () => {

    form.addOptionPackage.forEach(item => {
        service({
            url: `addOptionPackage/${item.id}`,
            method: "delete"
        })
    })
    getAddOptionPackageData()

}
// 获取加项包添加后的数据
const getAddedPackageData = () => {
    getAddOptionPackageData()
}
const handleSelectionChangeAddOptionPackage = (val: IaddOptionPackage[]) => {
    form.addOptionPackage.length = 0
    form.addOptionPackage.push(...val)

}
// 点击取消重置
const formReset = (formEl: FormInstance | undefined) => {
    dialogFormVisible.value = false
    if (!formEl) return
    formEl.resetFields()
}
// 点击确定按钮
const submit = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            form.province = (selectCityRef.value as any).provinceValue
            form.city = (selectCityRef.value as any).cityValue
            if (props.flagShowControl !== "editbutton") {
                service({
                    url: `/testHospitals`,
                    method: "post",
                    data: {
                        ...form,
                        ordernum: 0
                    }
                })
            } else if (props.flagShowControl === "editbutton") {
                service({
                    url: `/testHospitals/${props.getDataById}`,
                    method: "put",
                    data: {
                        ...form,
                    }
                })
            }

            formEl.resetFields()
            emit("addChange")
            dialogFormVisible.value = false
        } else {
            ElMessage({
                showClose: true,
                message: "请填写完整表单",
                type: "warning"
            })
            return false
        }
    })

}
watch(dialogFormVisible, () => {
    if (dialogFormVisible.value && props.flagShowControl === "editbutton") {
        service({
            url: `testHospitals/${props.getDataById}`,
        }).then(res => {
            if (res.data) {
                let key: keyof Iform;
                for (key in form) {
                    form[key] = res.data[key] as never
                }
            }
            (selectCityRef.value as any).provinceValue = form.province;
            (selectCityRef.value as any).cityValue = form.city;
        })

    }
})
</script>

<style scoped>
.el-button--text {
    margin-right: 15px;
}

.el-select {
    width: 300px;
}

.el-input {
    width: 300px;
}

/* 暂时无用 */
:deep(.el-dialog) {
    width: 1003px;
    height: 590px;

}

:deep(.el-dialog .el-dialog__header) {
    background-color: #F2F2F2;
    margin-right: 0;
    border-bottom: 1px solid #e4e4e4;
}

:deep(.el-dialog .el-dialog__header .el-dialog__title) {
    color: #333;
    font-size: 16px;
    font-weight: bold;
}

:deep(.el-dialog__body) {
    border-bottom: 1px solid #e4e4e4;
}

:deep(.el-checkbox-button__inner) {
    text-align: center;
    line-height: 32px;
    padding: 0;
    font-size: 13px;
}

.el-form {
    height: 420px;
    overflow: auto;
}

:deep(.el-form .el-form-item__label) {

    font-size: 12px;
    color: #000;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}


.el-button {

    box-sizing: border-box;
    width: 81px;
    height: 30px;
    border: 1px solid #cccccc;
    background-color: #fff;
    cursor: pointer;
    font-size: 12px;
    border-radius: 0;
    color: #000;
}

.editControl {
    width: 24px;
    height: 30px;
    padding: 0;
    margin: 0;
    color: #1abc9c;
    border: 0;
    background: rgba(255, 255, 255, 0);
}

.editControl:hover {
    text-decoration: underline;
    cursor: pointer;
}

.el-button:hover {
    background-color: rgb(242, 242, 242);
}

.demo-tabs>.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;

}

.baseInfo .top-box {
    display: flex;
}

.baseInfo .top-box .left-box {
    flex: 1;
}

.baseInfo .top-box .right-box {
    flex: 1;
}

:deep(.el-checkbox-button__inner) {
    width: 76px;
    height: 32px;
}

:deep(.el-transfer .el-transfer-panel) {
    width: 134px;
    height: 265px;

}

:deep(.el-transfer .el-transfer-panel .el-checkbox-group) {
    height: 158px;
    overflow: auto;
}

:deep(.el-transfer) {
    display: flex;
}

:deep(.el-transfer__buttons) {
    display: flex;
    flex-direction: column;
    padding: 0 5px;
    justify-content: center;
}

:deep(.el-transfer__buttons) button {
    width: 30px;
    height: 30px;
    border-radius: 50%;
}

:deep(.el-transfer__buttons) button:last-child {
    margin: 10px 0 0 0;
}

:deep(.el-transfer-panel .el-transfer-panel__header .el-checkbox .el-checkbox__label) {
    font-size: 13px;

}

.asterisk-left {
    margin-top: 10px;
}
</style>